package com.qckj.amz.domain.spapi.feeds.home.InventoryFeedXml;

import com.qckj.amz.domain.ProductFmlBasic;
import com.qckj.amz.domain.ProductFmlRlat;
import com.qckj.amz.domain.ProductInit;
import com.qckj.amz.domain.spapi.feeds.home.AmazonEnvelope;
import com.qckj.amz.domain.spapi.feeds.home.Header;
import com.qckj.amz.domain.spapi.feeds.home.Message;
import com.qckj.amz.utils.constants.AmzConstants;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author luchuan
 * @version v1.0
 * @date 2022/11/20 0020
 **/
public class CreateInventoryFeedXml {
    /**
     *
     * @param sellerId      卖家记号
     * @param productInit   产品常用属性
     * @param listProduct   产品信息
     * @return
     */
    public String getInventoryFeedXml(String sellerId, ProductInit productInit, List<Map<String, Object>> listProduct) {
        if (listProduct==null && listProduct.isEmpty()){
            return null;
        }

        ArrayList<Message> messageList = new ArrayList<>();//封装多个Message，即多个sku产品，无论是有无变体或多个不同的产品
        for (Map<String, Object> mapProduct: listProduct) {
            ProductFmlBasic basicObj = (ProductFmlBasic)mapProduct.get("basicObj");
            List<ProductFmlRlat> rlatList = (List<ProductFmlRlat>)mapProduct.get("rlatList");
            //封装多个变体
            for (ProductFmlRlat rlat:rlatList) {

                Inventory inventory = new Inventory();
                inventory.setSKU(rlat.getItemSku());
                inventory.setQuantity(String.valueOf(productInit.getQuantity()));
                inventory.setFulfillmentLatency("3");//完全延迟，具体属性不确定，百度查到这个一个延迟发货意思，1-30整数，默认填写3

                /**
                 * 二级/Message,此节点为List对象，可以包含主体、变体
                 */
                Message message = new Message();
                message.setMessageID(basicObj.getId());
                message.setOperationType(productInit.getUpdateDelete());//Update、delete
                message.setInventory(inventory);
                messageList.add(message);

            }

        }

        /**
         * 二级/Header
         */
        Header header = new Header();
        header.setDocumentVersion("1.01");
        header.setMerchantIdentifier(sellerId);

        /**
         * 一级/根节点AmazonEnvelope
         */
        AmazonEnvelope amazonEnvelope = new AmazonEnvelope();
        amazonEnvelope.setHeader(header);
        amazonEnvelope.setMessageType("Inventory");//Product、Price、Inventory
        amazonEnvelope.setMessage(messageList);

        /**
         * Javabean对象转换xml字符串
         */
        String xmlStr = AmzCommon.JavabeanToXmlStr(AmzConstants.FEED_TYPE_INVENTORY_FEED, amazonEnvelope);

        return xmlStr;
    }
}
